#property copyright "ID4"
#property link      "ID4"

int err;
int logfile;

// Global Variable
extern int WorkingPeriod = PERIOD_D1;

extern int SMAPeriod = 12;
extern int BarLimit = 2;
extern int OrdCheckLimit = 2;
//extern int iDelta = 5;

extern int unitsPerOrder = 5;
//double unitSize = 0.1;
extern int moneyManagementInPercent = 2;
int orderTicket = 0;
double currentUnitSize;
double p;
double spreadInPips;

double SMA;
double ATR;
double PriceHigh;
double PriceLow;
double oscRatio;
double trendRatio;
double totalRatio;

//bool bOSC;

double UnitHigh = 0.3;
double UnitLow = -0.3;
int iBarLimit;

//double Speed;

int TempOrdersHistoryTotal = 0;

int init()
{
  int factor = MathPow(10, MarketInfo(Symbol(),MODE_DIGITS) - 4);
  p = Point * factor;
  spreadInPips = MarketInfo(Symbol(),MODE_SPREAD) / factor;
  logfile=FileOpen("logfile.csv", FILE_CSV|FILE_WRITE, ',');
  return(0);   
}
int deinit()
{
  OrderPrintCSV();
  if(logfile > 0)
    FileClose(logfile);
  return(0);
}
  
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
  if(Bars < 100 || IsTradeAllowed() == false) return;
  OrderPrintCSV();
  Filter();
  if(OrdersTotal() > 0)
  {
    err = 0; 
  }
  else
  {
    if(OrdersTotal() == 0)
      CheckForSMA();
  }
  return(0);
}
//+------------------------------------------------------------------+
double GetUnitSize(double sl)
{
  sl *= 10000;
  double canLoss = AccountBalance()*moneyManagementInPercent*0.01;
  int canLossInPips = canLoss/((MarketInfo(Symbol(),MODE_TICKVALUE)));
  double lossPerPip = canLossInPips / sl;
  double temp = (lossPerPip/unitsPerOrder);
  int rounded = MathRound(temp*10);
  //Print("canlossinpips: ", canLossInPips, "lossPerPip: ", lossPerPip, "temp: ", temp, "rounded: ", rounded);
  temp = rounded;
  temp *= 0.1;
  double final = temp;
  //Print("temp: ", temp);
  if(temp<0.1)
     final = 0.1;
  //Print("UNIT SIZE: ", final);
  final = 0.2;                       // <----- change required
  return (final);
}
//+------------------------------------------------------------------+
void Filter()
{
  int i,j;
  int oscSum = 0;
  int trendSum = 0;
  int div = (1 + SMAPeriod) * SMAPeriod / 2;
  double smaHistory;
  SMA = iMA(NULL, WorkingPeriod, SMAPeriod, 0, MODE_SMA, PRICE_CLOSE, 1);
  ATR = iATR(NULL, WorkingPeriod, SMAPeriod, 1);
  PriceHigh = High[1];
  PriceLow = Low[1];
   
  for(i=1;i<=SMAPeriod;i++)
  {
    j = SMAPeriod - i + 1;
    smaHistory = iMA(NULL, WorkingPeriod, SMAPeriod, 0, MODE_SMA, PRICE_CLOSE, i);
    if(High[i] > smaHistory && Low[i] < smaHistory)
      oscSum += j;
    if(Low[i] > smaHistory)
      trendSum += j;
    if(High[i] < smaHistory)
      trendSum -= j;         
  }
  oscRatio = oscSum / div;
  trendRatio = MathAbs(trendSum) / div;
  totalRatio = oscRatio + trendRatio;
}
//+------------------------------------------------------------------+
void CheckForSMA()
{
  double newSL = 0;
  double newTP = 0;
//   double Unit = MathMax(UnitHigh - UnitLow, 0.618);
  double Unit = 0.618;
   
  currentUnitSize = GetUnitSize(ATR * Unit * 1.5);

//   if((UnitLow < 0.3 && Ask < SMA + ATR * UnitLow))// ||
//     (UnitLow >= 0.3 && Ask > SMA + ATR * UnitLow))
  if(Ask < SMA + ATR * UnitLow)
  {
    newSL = Ask - ATR * Unit * 1;
    newTP = Ask + ATR * Unit * 1;
    iBarLimit = BarLimit;
    orderTicket = OrderSend(Symbol(), OP_BUY, currentUnitSize * unitsPerOrder, Ask, 5, newSL, newTP);
  }
   
//   if((UnitHigh > -0.3 && Bid > SMA + ATR * UnitHigh))// ||
//     (UnitHigh <= -0.3 && Bid < SMA + ATR * UnitHigh))
  if(Bid > SMA + ATR * UnitHigh)
  {
    newSL = Bid + ATR * Unit * 1;
    newTP = Bid - ATR * Unit * 1;
    iBarLimit = BarLimit;
    orderTicket = OrderSend(Symbol(), OP_SELL, currentUnitSize * unitsPerOrder, Bid, 5, newSL, newTP);
  }  
}
//+------------------------------------------------------------------+
string ExcelDateFormat(datetime dt)
{
  return (StringSetChar(StringSetChar(TimeToStr(dt),4,'-'),7,'-'));
}
//+------------------------------------------------------------------+
void OrderPrintCSV()
{
  if(logfile > 0)
  {
    int hstTotal = OrdersHistoryTotal();
    if(hstTotal != TempOrdersHistoryTotal)
    {
      TempOrdersHistoryTotal = hstTotal;
      if(OrderSelect(hstTotal - 1, SELECT_BY_POS,MODE_HISTORY)==true)
      {
        //OrderPrint();      
        FileWrite(logfile, OrderTicket(),
                           ExcelDateFormat(OrderOpenTime()),
                           OrderType(),
                           OrderLots(),
                           OrderOpenPrice(),
                           OrderStopLoss(),
                           OrderTakeProfit(),
                           ExcelDateFormat(OrderCloseTime()),
                           OrderClosePrice(),
                           OrderCommission(),
                           OrderSwap(),
                           OrderProfit(),
                           OrderComment(),
                           OrderMagicNumber(),
                           OrderExpiration());
      }
    }
  }   
}
//+------------------------------------------------------------------+

